package com.itelite.common.util;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.itelite.common.info.Result;
import com.itelite.domain.pojo.User;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.GrantedAuthority;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;

/**
 * Created by echisan on 2018/6/23
 */
@Slf4j
public class JwtTokenUtils {

    public static final String TOKEN_HEADER = "Authorization";
    public static final String TOKEN_PREFIX = "Bearer ";

    private static final String SECRET = "syItelite";
    private static final String ISS = "Shenyang";

    public static final String USER_ROLE = "USER_ROLE";
    public static final String USER_NAME = "USER_NAME";
    public static final String USER_REAL_NAME = "USER_REAL_NAME";
    public static final String USER_ID = "USER_ID";
    public static final String USER_GROUPID = "USER_GROUPID";

    // 过期时间是3600秒，既是1个小时
    private static final long EXPIRATION = 7200L;

    // 选择了记住我之后的过期时间为7天
    private static final long EXPIRATION_REMEMBER = 604800L;

    // 创建token
    public static String createToken(String subject,HashMap<String,Object> claims,boolean isRememberMe) {
        long expiration = isRememberMe ? EXPIRATION_REMEMBER : EXPIRATION;
        return Jwts.builder()
                .signWith(SignatureAlgorithm.HS512, SECRET)
                .setClaims(claims)
                .setIssuer(ISS)
                .setSubject(subject)
                .setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis() + expiration * 1000))
                .compact();
    }

    private static Claims getTokenBody(String token){
        return Jwts.parser()
                .setSigningKey(SECRET)
                .parseClaimsJws(token)
                .getBody();
    }

    //解析token并获取我们存放的信息
    public static HashMap<String, Object> getUserInfo(String token, String...infos){
        HashMap<String,Object> hashMap = new HashMap<>();
        if(infos!=null){
            Claims claims = getTokenBody(token);
            for (String info : infos) {
                hashMap.put(info,claims.get(info));
            }
        }
        return hashMap;
    }
    //解析token并获取我们存放的信息
    public static HashMap<String, Object> getUserInfo(String token){
        return getUserInfo(token,USER_NAME,USER_ID,USER_REAL_NAME,USER_ROLE,USER_GROUPID);
    }

    // 是否已过期
    public static boolean isExpiration(String token) {
        try {
            return getTokenBody(token).getExpiration().before(new Date());
        } catch (ExpiredJwtException e) {
            return true;
        }
    }

    public static void createJwt(User user, int rememberMe, HttpServletResponse response) throws IOException {
        boolean isRemember = rememberMe == 1;
        Collection<? extends GrantedAuthority> authorities = user.getAuthorities();
        String role = null;
        for (GrantedAuthority authority : authorities) {
            role = authority.getAuthority();
        }
        HashMap<String,Object> claims = new HashMap<>();
        claims.put("USER_ROLE",role);
        claims.put("USER_NAME",user.getUsername());
        claims.put("USER_REAL_NAME",user.getRealName());
        claims.put("USER_ID",user.getUserId());
        claims.put("USER_GROUPID",user.getGroupId());
        String token = JwtTokenUtils.createToken(user.getUsername(),claims , isRemember);
//        String token = JwtTokenUtils.createToken(jwtUser.getUsername(), false);
        // 返回创建成功的token
        // 但是这里创建的token只是单纯的token
        // 按照jwt的规定，最后请求的时候应该是 `Bearer token`
        //根据配置中来选择是执行跳转,还是返回字符串
        response.setContentType("application/json;charset=UTF-8");
        response.setHeader("token", JwtTokenUtils.TOKEN_PREFIX + token);
        response.getWriter().write(new ObjectMapper().writeValueAsString(Result.success().build().data("user",user)));
    }
}
